/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  DatePicker,
  Form,
  Icon,
  Input,
  InputNumber,
  Modal,
  notification,
  Select,
  Upload
} from 'antd';

import {FormField, FormLayout, ModalFooter} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import ViewTitle from "../../../components/ViewTitle";

import notify from "../../../components/NotificationExtra";
import TextArea from "antd/es/input/TextArea";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            dict,
            dic, finance, vendor, customer
          }) => ({...tenant, ...dic, ...dict, ...global, ...finance, ...vendor, ...customer}))
export default class ModalCreateOrEditPaymentRecord extends FormBase {
  constructor(props) {
    super(props);
    const {values = {}, customers = [], vendors = []} = this.props;
    this.state = {customers, vendors, ...values};
  }

  componentDidMount() {
    const {table} = this.props;
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });

    this.onDataLoad().then(res => this.setState(res));
  }

  async onDataLoad() {
    const {accountCode} = this.state;
    const accountRes = await this.props.dispatch({
      type: 'finance/findAccounts',
      payload: {}
    });
    const accounts = accountRes.result;

    this.setState({accounts});
  }

  renderFoot = () => {
    const {foot, value, callback, modalRef, form, order = {}} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              const {
                fileList,
                _accountName,
                customer,
                customerCode,
                vendor = order.vendor,
                vendorCode = order.vendorCode,
                vendorName = order.vendorName,
                accountCode
              } = this.state;
              values._accountName = _accountName;
              values.accountCode = accountCode;
              values.customer = customer;
              values.customerCode = customerCode;
              values.vendor = vendor;
              values.vendorCode = vendorCode;
              values.vendorName = vendorName;
              values.orderCode = order.code;
              values.fileList = fileList;

              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };
  getBankOpt = () => {
    const {accounts = []} = this.state;
    const temp = [];
    _.map(accounts, item => {
      const {code, accountName, openingBank, account} = item;
      temp.push(<Option key={code} value={accountName + " " + openingBank + " " + account}>
        {accountName + " " + openingBank + " " + account}
      </Option>);
    });
    return temp;
  };

  getOpt = (title) => {
    const {customers = [], vendors = []} = this.state;
    const list = title === '收入' ? customers : vendors;
    return list.map(opt => (<Option key={opt.code} value={opt.name}>
        {opt.name}
      </Option>
    ));
  };

  getTargetView = () => {
    const {target = '个人', targetMan, targetDept, vendorName} = this.state;
    const {vendors = []} = this.props;
    const view = <FormField label={'人员'}
                            name={'targetMan'}
                            initialValue={targetMan}>
      <Input style={{width: '100%'}}></Input>
    </FormField>;
    if (target === '公司') {
      return <FormField label={'公司'}
                        name={'vendorName'}
                        initialValue={vendorName}>
        <AutoComplete style={{width: '100%'}}
                      dataSource={this.getCustomerOpt(vendors)}
                      allowClear
                      onChange={value => {
                        if (!value) {
                          this.state['vendorName'] = '';
                          this.state['vendorCode'] = '';
                        }
                      }}
                      onSelect={(value, option) => {
                        const {key, props} = option;
                        this.state['vendorCode'] = key;
                        this.state['vendorName'] = value;
                      }}
        >
        </AutoComplete>
      </FormField>;
    }
    if (target === '部门') {
      const temp = [];
      temp.push(<FormField label={'部门'}
                           name={'targetDept'}
                           initialValue={targetDept}>
        <Input style={{width: '100%'}}></Input>
      </FormField>);
      temp.push(<FormField label={'人员'}
                           name={'targetMan'}
                           initialValue={targetMan}>
        <Input style={{width: '100%'}}></Input>
      </FormField>);
      return temp;
    }
    return view;
  };

  getEndDataView = () => {
    const {treeNode = {}, isDetail = false} = this.props;
    let {memo, endDate} = this.state;
    const {name} = treeNode;
    const temp = [];
    if (name === '投标/履约保证金') {
      temp.push(<FormField
          label={'截至日期'}
          name={'endDate'}
          initialValue={endDate ? moment(endDate) : undefined}
        >
          <DatePicker disabled={isDetail} style={{width: '100%'}}></DatePicker>
        </FormField>
      );
    }
    temp.push(
      <FormField
        label={"备注"}
        name={'memo'}
        initialValue={memo}
      >
        <TextArea
        ></TextArea>
      </FormField>
    );
    return temp;
  };

  render() {
    const {
      form,
      table,
      isDetail = false,
      treeNode = {}, vendors = []
    } = this.props;

    const {name, mark} = treeNode;
    const isProcure = mark === 'TRE-PROCURE-MAIN' || mark === 'TRE-PROCURE-AUX';
    const model = this.props[`${table}Model`];

    let {
      code,
      date = moment(),
      accountName,
      openingBank,
      account,
      target = '个人',
      paymentMatter = name,
      paymentAmount = 0,
      payWay, targetDept, targetMan, vendorName,
      fileList,
      previewVisible,
      previewImage,
      balance = 0, taxRate = '13%'
      // division = values ? values.division : ''
    } = this.state;
    const tax = this.getTax(paymentAmount, taxRate);
    return (
      <Form>
        {isProcure && <FormLayout form={form} cols={2}>

        </FormLayout>}
        <ViewTitle
          title={'付款账户信息'}
        ></ViewTitle>
        <FormLayout form={form} cols={2}>
          <FormField
            label={'编码'}
            name={'code'}
            required={true}
            disabled={true}
            initialValue={code ? code : 'FIN' + new moment().format('YYYYMMDDHHmmss')}
          >
            <Input disabled={true} style={{width: '100%'}}
            ></Input>
          </FormField>

          <FormField
            label={'户名'}
            name={'accountName'}
            required={true}
            initialValue={accountName}
          >
            <AutoComplete disabled={isDetail} style={{width: '100%'}}
                          dataSource={this.getBankOpt()}
                          allowClear
                          onChange={value => {
                            if (!value) {
                              this.state.accountCode = '';
                              this.state.account = '';
                              this.state.openingBank = '';
                              this.state._accountName = '';
                              form.setFieldsValue({openingBank: undefined, account: undefined});
                            }
                          }}
                          onSelect={(value, option) => {
                            const {accounts} = this.state;
                            const {key} = option;
                            _.map(accounts, item => {
                              const {code, accountName, account, openingBank, balance = 0} = item;
                              if (code === key) {
                                this.state.accountCode = code;
                                this.state.account = account;
                                this.state.openingBank = openingBank;
                                this.state._accountName = accountName;
                                this.state.balance = balance;
                                form.setFieldsValue({openingBank, account, balance});
                              }
                            });
                            this.componentDidMount();
                          }}
            >
            </AutoComplete>

          </FormField>
          <FormField
            label={'开户行'}
            name={'openingBank'}
            required={true}
            initialValue={openingBank}
          >
            <Input disabled style={{width: '100%'}}
            ></Input></FormField>
          <FormField
            label={'账号'}
            name={'account'}
            required={true}
            initialValue={account}
          >
            <Input disabled style={{width: '100%'}}
            ></Input></FormField>
          <FormField
            label={'账户结余'}
            name={'balance'}
            initialValue={balance}
          >
            <InputNumber disabled style={{width: '100%'}}
            ></InputNumber>
          </FormField>
        </FormLayout>

        {
          <ViewTitle
            title={'支出信息'}
          ></ViewTitle>}

        {<FormLayout form={form} cols={2}>
          <FormField
            label={'支出去向'}
            name={'target'}
            initialValue={target}
          >
            <Select disabled={isDetail} style={{width: '100%'}} onSelect={value => {
              this.state.target = value;
            }}
            >
              {this.getModelOption(model, 'target')}
            </Select>
          </FormField>
          <FormField label={'公司'}
                     name={'vendorName'}
                     initialValue={vendorName}>
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getCustomerOpt(vendors)}
                          allowClear
                          onChange={value => {
                            if (!value) {
                              this.state['vendorName'] = '';
                              this.state['vendorCode'] = '';
                            }
                          }}
                          onSelect={(value, option) => {
                            const {key, props} = option;
                            this.state['vendorCode'] = key;
                            this.state['vendorName'] = value;
                          }}
            >
            </AutoComplete>
          </FormField>

          <FormField label={'部门'}
                     name={'targetDept'}
                     initialValue={targetDept}>
            <Input style={{width: '100%'}}></Input>

          </FormField>

          <FormField label={'人员'}
                     name={'targetMan'}
                     initialValue={targetMan}>
            <Input style={{width: '100%'}}></Input>
          </FormField>

          <FormField
            label={'日期'}
            name={'date'}
            required={true}
            initialValue={date ? moment(date) : undefined}
          >
            <DatePicker disabled={isDetail} style={{width: '100%'}}></DatePicker>
          </FormField>
          <FormField
            label={'支出事由'}
            name={'paymentMatter'}
            initialValue={paymentMatter}
          >
            <Input disabled={isDetail} style={{width: '100%'}}
            ></Input>
          </FormField>

          <FormField
            label={'支出付款方式'}
            name={'payWay'}
            initialValue={payWay}
          >
            {/*<Select disabled={isDetail || noPayWay} style={{width: '100%'}}*/}
            <Select disabled={isDetail} style={{width: '100%'}}
            >
              {this.getModelOption(model, 'payWay')}
            </Select>
          </FormField>
          {/*<FormField*/}
          {/*  label={'货币形式'}*/}
          {/*  name={'moneyType'}*/}
          {/*  initialValue={moneyType}*/}
          {/*>*/}
          {/*  <Select disabled={isDetail} style={{width: '100%'}}*/}
          {/*  >*/}
          {/*    {this.getModelOption(model, 'moneyType')}*/}
          {/*  </Select>*/}
          {/*</FormField>*/}
          <FormField
            label={'支出金额'}
            name={'paymentAmount'}
            initialValue={paymentAmount}
            required={true}
          >
            <InputNumber disabled={isDetail} style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'税率'}
            name={'taxRate'}
            required={true}
            initialValue={taxRate}
          >
            <Select allowClear style={{width: '100%'}}>
              {this.getSelectOption(this.taxRateOption)}
            </Select>
          </FormField>
          {/*<FormField*/}
          {/*  label={'税额'}*/}
          {/*  name={'tax'}*/}
          {/*  initialValue={tax}*/}
          {/*  required={true}*/}
          {/*>*/}
          {/*  <InputNumber disabled style={{width: '100%'}}*/}
          {/*  ></InputNumber>*/}
          {/*</FormField>*/}
          {this.getEndDataView()}
        </FormLayout>}

        {
          <div style={{marginLeft: '64px'}}>
            <Upload
              action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
              listType="picture-card"
              fileList={fileList}
              accept={".png,.jpg"}
              onPreview={this.picHandlePreview}
              onChange={this.picHandleChange}
              onDownload={file => {
                console.log('ondownlad', file);
              }}
              beforeUpload={(file, fileList) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  notify({type: 'error', message: '文件过大！'});
                  return isLt2M;
                }
                return false;
              }}
            >
              {<div>
                <Icon type="plus"/>
                <div className="ant-upload-text">上传图片</div>
              </div>}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={() => {
              this.setState({previewVisible: false});
            }}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </div>
        }
        {this.renderFoot()}
      </Form>
    );
  }
}

